"""Simple echo server.

$ python3 echo_server.py
$ nc -C localhost 8013
"""

import telnetlib

import diesel

import eof.txbr as txbr
import eof.txbr.reactor as reactor
import eof.ztk as ztk

ztk.loadZCML(txbr)


BREAK = telnetlib.IAC + telnetlib.BRK


class Echo(txbr.Protocol):
	def connectionMade(self):
		pass

	def dataReceived(self, data):
		if BREAK in data:
			data, _ = data.split(BREAK, 1)
			close = True
		else:
			close = False

		if data.strip() == b'quit':
			close = True
		else:
			self.transport.write(b'you said ' + data)

		if close:
			self.transport.loseConnection()


class EchoFactory(txbr.ServerFactory):
	protocol = Echo


app = diesel.Application()
reactor.install(app)
reactor.listenTCP(8013, EchoFactory())
app.run()
